package com.yunchuang.controller.user;

import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.yunchuang.model.dto.UserUpdateDto;
import com.yunchuang.service.UserService;
import com.yunchuang.service.impl.UserServiceImpl;
import com.yunchuang.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 用户修改信息
 *
 * @author ItJiange
 * @date 2023/10/25
 */
@WebServlet("/user/update")
public class UserUpdateController extends HttpServlet {
    private final Logger logger= LoggerFactory.getLogger("logback");
    private final UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数并解析为 UserUpdateDto 对象
        BufferedReader reader = req.getReader();
        String userJson = reader.readLine();
        UserUpdateDto userUpdateDto = JSONUtils.jsonToObject(userJson, UserUpdateDto.class);
//        Gson gson = new Gson();
//        UserUpdateDto userUpdateDto = gson.fromJson(userJson, UserUpdateDto.class);
        // 校验
        if (StrUtil.isEmptyIfStr(userUpdateDto)) {
            logger.info("修改字段为空！");
            return;
        }
        // 修改用户
        boolean flag = userService.userUpdate(userUpdateDto);
        if (!flag) {
            logger.info("修改失败！");
            return;
        }
        logger.info("修改成功！");
        resp.sendRedirect("/login.html");
    }
}
